import axios from 'axios'
import qs from 'qs'
import utils from './utils.js'
import {Message} from 'element-ui'
// Vue.prototype.$message = Message
import Vue from 'vue'
import router from '../../router/index.js'; //路由文件

// 请求拦截器
axios.interceptors.request.use(function (config) {
  // if (!config.params) {
  //   config.params = {}
  // }
  config.headers['authorization'] = utils.getLocalStorage('usertoken')
  return config

}, error => {
  return Promise.resolve(error)
})


// 响应拦截器
axios.interceptors.response.use((response) => {
  if (response.data.succeed) {
    return response
  } else {
    if (response.data.data) {
      Message.error(response.data.data.ErrMsg)
      return response
    } else if (response.data.errorMessage) {
      Message.error(response.data.errorMessage)
      console.log(response.data.errorMessage)
      if (response.data.errorMessage == '用户已在其它位置登陆！'){
        router.push({ //返回登录
          path: 'login'
        })
      }
      return response
    } else {
      router.push({ //返回登录
        path: 'login'
      })
    }
  }
}, error => {
  if (!error.response) {
    // MessageBox.alert('系统异常','提示')
    return false
  }
  return Promise.resolve(error)
})


export default {
	get (url, data) {
		return axios.get(url, {
			params: data,
		}).then((res) => {
			return res
		})
	},
  post (url, data) {
    return axios({
      method: 'post',
      baseURL: process.env.BASE_URL,
      url: url,
      data: qs.stringify(data),
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      timeout: 10000
    }).then((res) => {
        return res
    })
  }
}

export function get(url, data = {}) {
  return new Promise((resolve,reject) => {
    axios.get(url, {params:data}).then(response =>{
      resolve(response)
    }), err => {
      reject(err)
    }
  })
}

export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data).then(response =>{
      resolve(response)
    }), err => {
      reject(err)
    }
  })
}

Vue.prototype.$get = get
Vue.prototype.$post = post

